package dao;

import pojo.Player;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class UserDao {
    //文件[users]中所有的用户都存在此集合中 //Player的id从0开始
    private static List<Player> players=getAllPlayers();
    //文件[user]的位置
    private static final String filePath="src/main/resources/users";

    /*
    负责人：李季岭
    功能：文件[users]的所有json对象转为Player对象，返回Player对象集合
    参数值：void
    返回值：Player对象集合
    */
    public static List<Player> getAllPlayers(){
        try (
                ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath))
        ){
            players=(List<Player>) ois.readObject();
        } catch (Exception e) {
            return new ArrayList<>();
        }
        return players;
    }

    /*
        负责人：李季岭
        功能：根据账号名返回对应的Player对象
        参数：name 要查找的账号名
        返回值：返回Player对象
     */
    public static Player findPlayer(String name) {
        for (Player player : players) {
            if(player.getName().equals(name)){
                return player;
            }
        }
        return null;
    }

    /*
        负责人：李季岭
        功能：将Player对象写入文件[user]中
             注意：1.要将p的id属性赋值
                  2.添加到players集合
                  3.写入文件
        参数：p 要写入的对象
        返回值：void
     */
    public static void insertPlayer(Player p) {
        p.setId(players.size());
        players.add(p);

        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath))){
            oos.writeObject(players);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /*
        负责人：李季岭
        功能：修改原来id为p.id的对象为p对象 对文件也进行相应修改
        参数： p 修改后的对象
        返回值：void
     */
    public static void changePlayer(Player p) {
        int i=p.getId();
        players.remove(i);
        players.add(i,p);
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath))){
            oos.writeObject(players);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
